(function() {
    $.fn.paginate = function(options) {
        var opts = $.extend({}, $.fn.paginate.defaults, options);
        return this.each(function() {
            $this = $(this);
            var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
            var selectedpage = o.start;
            $.fn.draw(o,$this,selectedpage);    
        });
    };
    var outsidewidth_tmp = 0;
    var insidewidth      = 0;
    var bName = navigator.appName;
    var bVer = navigator.appVersion;
    if(bVer.indexOf('MSIE 7.0') > 0)
        var ver = "ie7";
    $.fn.paginate.defaults = {
        count       : 5,
        start       : 12,
        display     : 5,
        border                  : true,
        border_color            : '#fff',
        text_color              : '#8cc59d',
        background_color        : 'black',  
        border_hover_color      : '#fff',
        text_hover_color        : '#fff',
        background_hover_color  : '#fff', 
        rotate                  : true,
        images                  : true,
        mouse                   : 'slide',
        onChange                : function(){return false;}
    };
    $.fn.draw = function(o,obj,selectedpage){
        if(o.display > o.count)
            o.display = o.count;
        $this.empty();
        if(o.images){
            var spreviousclass  = 'jPag-sprevious-img';
            var previousclass   = 'jPag-previous-img';
            var snextclass      = 'jPag-snext-img';
            var nextclass       = 'jPag-next-img';
        }
        else{
            var spreviousclass  = 'jPag-sprevious';
            var previousclass   = 'jPag-previous';
            var snextclass      = 'jPag-snext';
            var nextclass       = 'jPag-next';
        }
        var _first      = $(document.createElement('a')).addClass('jPag-first').html('首页');
        
        if(o.rotate){
            if(o.images) var _rotleft   = $(document.createElement('span')).addClass(spreviousclass);
            else var _rotleft   = $(document.createElement('span')).addClass(spreviousclass).html('&laquo;');       
        }
        
        var _divwrapleft    = $(document.createElement('div')).addClass('jPag-control-back');
        _divwrapleft.append(_first).append(_rotleft);
        
        var _ulwrapdiv  = $(document.createElement('div')).css('overflow','hidden');
        var _ul         = $(document.createElement('ul')).addClass('jPag-pages')
        var c = (o.display - 1) / 2;
        var first = selectedpage - c;
        var selobj;
        for(var i = 0; i < o.count; i++){
            var val = i+1;
            if(val == selectedpage){
                var _obj = $(document.createElement('li')).html('<span class="jPag-current">'+val+'</span>');
                selobj = _obj;
                _ul.append(_obj);
            }   
            else{
                var _obj = $(document.createElement('li')).html('<a>'+ val +'</a>');
                _ul.append(_obj);
                }               
        }       
        _ulwrapdiv.append(_ul);
        
        if(o.rotate){
            if(o.images) var _rotright  = $(document.createElement('span')).addClass(snextclass);
            else var _rotright  = $(document.createElement('span')).addClass(snextclass).html('&raquo;');
        }
        
        var _last       = $(document.createElement('a')).addClass('jPag-last').html('尾页');
        var _divwrapright   = $(document.createElement('div')).addClass('jPag-control-front');
        _divwrapright.append(_rotright).append(_last);
        
        //append all:
        $this.addClass('jPaginate').append(_divwrapleft).append(_ulwrapdiv).append(_divwrapright);
            
        if(!o.border){
            if(o.background_color == 'none') var a_css              = {'color':o.text_color};
            else var a_css                                          = {'color':o.text_color,'background-color':o.background_color};
            if(o.background_hover_color == 'none')  var hover_css   = {'color':o.text_hover_color};
            else var hover_css                                      = {'color':o.text_hover_color,'background-color':o.background_hover_color}; 
        }   
        else{
            if(o.background_color == 'none') var a_css              = {'color':o.text_color,'border':'1px solid '+o.border_color};
            else var a_css                                          = {'color':o.text_color,'background-color':o.background_color,'border':'1px solid '+o.border_color};
            if(o.background_hover_color == 'none')  var hover_css   = {'color':o.text_hover_color,'border':'1px solid '+o.border_hover_color};
            else var hover_css                                      = {'color':o.text_hover_color,'background-color':o.background_hover_color,'border':'1px solid '+o.border_hover_color};
        }
        
        $.fn.applystyle(o,$this,a_css,hover_css,_first,_ul,_ulwrapdiv,_divwrapright);
        //calculate width of the ones displayed:
        var outsidewidth = outsidewidth_tmp - _first.parent().width() -3;
        if(ver == 'ie7'){
            _ulwrapdiv.css('width',outsidewidth+72+'px');
            _divwrapright.css('left',outsidewidth_tmp+6+72+'px');
        }
        else{
            _ulwrapdiv.css('width',outsidewidth+'px');
            _divwrapright.css('left',outsidewidth_tmp+6+'px');
        }
        
        if(o.rotate){
            _rotright.hover(
                function() {
                  thumbs_scroll_interval = setInterval(
                    function() {
                      var left = _ulwrapdiv.scrollLeft() + 1;
                      _ulwrapdiv.scrollLeft(left);
                    },
                    20
                  );
                },
                function() {
                  clearInterval(thumbs_scroll_interval);
                }
            );
            _rotleft.hover(
                function() {
                  thumbs_scroll_interval = setInterval(
                    function() {
                      var left = _ulwrapdiv.scrollLeft() - 1;
                      _ulwrapdiv.scrollLeft(left);
                    },
                    20
                  );
                },
                function() {
                  clearInterval(thumbs_scroll_interval);
                }
            );
            if(o.mouse == 'press'){
                _rotright.mousedown(
                    function() {
                      thumbs_mouse_interval = setInterval(
                        function() {
                          var left = _ulwrapdiv.scrollLeft() + 5;
                          _ulwrapdiv.scrollLeft(left);
                        },
                        20
                      );
                    }
                ).mouseup(
                    function() {
                      clearInterval(thumbs_mouse_interval);
                    }
                );
                _rotleft.mousedown(
                    function() {
                      thumbs_mouse_interval = setInterval(
                        function() {
                          var left = _ulwrapdiv.scrollLeft() - 5;
                          _ulwrapdiv.scrollLeft(left);
                        },
                        20
                      );
                    }
                ).mouseup(
                    function() {
                      clearInterval(thumbs_mouse_interval);
                    }
                );
            }
            else{
                _rotleft.click(function(e){
                    var width = outsidewidth - 10;
                    var left = _ulwrapdiv.scrollLeft() - width;
                    _ulwrapdiv.animate({scrollLeft: left +'px'});
                }); 
                
                _rotright.click(function(e){
                    var width = outsidewidth - 10;
                    var left = _ulwrapdiv.scrollLeft() + width;
                    _ulwrapdiv.animate({scrollLeft: left +'px'});
                });
            }
        }
        
        //first and last:
        _first.click(function(e){
                _ulwrapdiv.animate({scrollLeft: '0px'});
                _ulwrapdiv.find('li').eq(0).click();
        });
        _last.click(function(e){
                _ulwrapdiv.animate({scrollLeft: insidewidth +'px'});
                _ulwrapdiv.find('li').eq(o.count - 1).click();
        });
        
        //click a page
        _ulwrapdiv.find('li').click(function(e){
            selobj.html('<a>'+selobj.find('.jPag-current').html()+'</a>'); 
            var currval = $(this).find('a').html();
            $(this).html('<span class="jPag-current">'+currval+'</span>');
            selobj = $(this);
            $.fn.applystyle(o,$(this).parent().parent().parent(),a_css,hover_css,_first,_ul,_ulwrapdiv,_divwrapright);  
            var left = (this.offsetLeft) / 2;
            var left2 = _ulwrapdiv.scrollLeft() + left;
            var tmp = left - (outsidewidth / 2);
            if(ver == 'ie7')
                _ulwrapdiv.animate({scrollLeft: left + tmp - _first.parent().width() + 52 + 'px'}); 
            else
                _ulwrapdiv.animate({scrollLeft: left + tmp - _first.parent().width() + 'px'});  
            o.onChange(currval);    
        });
        
        var last = _ulwrapdiv.find('li').eq(o.start-1);
        last.attr('id','tmp');
        var left = document.getElementById('tmp').offsetLeft / 2;
        last.removeAttr('id');
        var tmp = left - (outsidewidth / 2);
        if(ver == 'ie7') _ulwrapdiv.animate({scrollLeft: left + tmp - _first.parent().width() + 52 + 'px'});    
        else _ulwrapdiv.animate({scrollLeft: left + tmp - _first.parent().width() + 'px'}); 
    }
    
    $.fn.applystyle = function(o,obj,a_css,hover_css,_first,_ul,_ulwrapdiv,_divwrapright){
                    obj.find('a').css(a_css);
                    obj.find('span.jPag-current').css(hover_css);
                    obj.find('a').hover(
                    function(){
                        $(this).css(hover_css);
                    },
                    function(){
                        $(this).css(a_css);
                    }
                    );
                    obj.css('padding-left',_first.parent().width() + 5 +'px');
                    insidewidth = 0;
                    
                    obj.find('li').each(function(i,n){
                        if(i == (o.display-1)){
                            outsidewidth_tmp = this.offsetLeft + this.offsetWidth ;
                        }
                        insidewidth += this.offsetWidth;
                    })
                    _ul.css('width',insidewidth+'px');
    }
})();

/************************************************** 构造函数 **************************************************************/
(function(){

    
    var JZMap;

    var jMap = function(cons){
        this.cons = cons;
    };
    jMap.prototype = {
        // init map
        init: function(){
            var that =this;
            that.initMap();
        },
        // set point
        getPoint:function(){
            var  that =this;
            // 考虑其它地区
            // var selectedCity = $('.city .text').text();  
            var myGeo = new BMap.Geocoder();
            myGeo.getPoint('厦门', function(point){
                if (point) {
                    that.setMap(point,12);
                    that.cons.doGet(true);
                }else{
                    var point=new BMap.Point(0,0);
                    that.setMap(point,12);
                    that.cons.doGet(true);
                }
            });
        },
        iniMapDataRender:function(json){

            var  that =this;
            that.removeOverlay();
            var markerArr = json, points=[];
            // data import
            for (var i = 0; i < markerArr.length; i++) {
                var json=markerArr[i];
                var txt = markerArr[i].name;
                var pintx = markerArr[i].longitude;
                var pinty = markerArr[i].latitude;
                var count= markerArr[i].count;
                that.addOverlayToMap(new BMap.Point(pintx, pinty),txt,count);
                points.push(new BMap.Point(pintx, pinty));
            }
            JZMap.setViewport(points);
            
        },
        getMapGeocoder:function(str){

            var that = this;
            try{
                var myGeo = new BMap.Geocoder();
                myGeo.getPoint(str, function(point){
                    if (point) {
                        // console.log(str);
                        that.cons.searchAround(point);
                    }else{
                        // return alert('没有搜索到房源');
                        // console.log(point);
                        modal();
                    }
                    // console.log(point);
                }, "厦门");
            }
            catch(e)
            {
                console.log(e);
                modal();
            }
            // console.log(str);
                // 将地址解析结果显示在地图上,并调整地图视野
                
        },
        addMaxMin:function(){
            // 百度地图API功能
                // var map = new BMap.Map("allmap");
                // map.centerAndZoom(new BMap.Point(116.404, 39.915), 11);

                var top_left_control = new BMap.ScaleControl({anchor: BMAP_ANCHOR_BOTTOM_LEFT});// 左上角，添加比例尺
                var top_left_navigation = new BMap.NavigationControl();  //左上角，添加默认缩放平移控件
                // var top_right_navigation = new BMap.NavigationControl({anchor: BMAP_ANCHOR_TOP_RIGHT, type: BMAP_NAVIGATION_CONTROL_SMALL}); //右上角，仅包含平移和缩放按钮
                 
                JZMap.addControl(top_left_control);        
                JZMap.addControl(top_left_navigation);     
                // JZMap.addControl(top_right_navigation);    
                
                
        },
        addOverlayToMap:function(point,text,count){
                var ep =this;
                function ComplexCustomOverlay(point,text,count){
                    this._point = point;
                    this._text = text;
                    this._count =count;
                }
                ComplexCustomOverlay.prototype = new BMap.Overlay();
                ComplexCustomOverlay.prototype.initialize = function(map,type){
                    this._map = JZMap;

                    var div = this._div = $("<div>")[0];
                    $(div).css({
                        'position': "absolute",
                        'cursor'  : "pointer",
                        'z-index'  : BMap.Overlay.getZIndex(this._point.lat),
                    })

                    $(div).on('mouseover' ,function(){

                        var cur = $(this);
                        cur.addClass('light')
                        var Index = cur.css('z-index') < 0? cur.css('z-index')*(-1): cur.css('z-index');
                        cur.css({"z-index":Index});
                    
                    })
                    $(div).on('mouseout' ,function(){

                        var cur = $(this);
                        cur.removeClass('light')
                        var Index = cur.css('z-index') < 0? cur.css('z-index'): cur.css('z-index')*(-1);
                        cur.css({"z-index":Index});
                        
                    })
                    
                    // mark
                    $(div).addClass('map-div');
                   
                    // var span = this._span = $('<span>')[0];
                    var staff = $('<div class ="map-tag">')[0];
                    var i= this._i = $('<i>')[0];
                    // var unit= this._unit = $('<span>')[0];

                    // div.appendChild(span);
                    div.appendChild(i);
                    div.appendChild(staff);
                    // div.appendChild(unit);

                    // $(span).text(this._text);
                    $(staff).text(this._text +' '+ this._count + '间'); 
                    $(i).text(this._count); 
                    // $(unit).text("间"); 
                
                    JZMap.getPanes().markerPane.appendChild(div);

                    // fix bug
                    if($(div).hasClass('map-div')){
                        
                        $(div).css({
                            'margin-top': $(div).height()*(-1),
                            'margin-left': ($(div).width()/2)*(-1)
                        })
                        
                    }
                    return div;
            }
            //mark
            ComplexCustomOverlay.prototype.draw = function(){

                var JZMap = this._map;
                var pixel = JZMap.pointToOverlayPixel(point);
                $(this._div).css({
                    'left': (pixel.x) + "px",
                    'top': (pixel.y) + "px",
                }) 
                
            }
            ComplexCustomOverlay.prototype.addEventListener = function(event,fun){
                this._div['on'+event] = fun;
            }
            // add layer
            var marker=new ComplexCustomOverlay(new BMap.Point(point.lng,point.lat),text,count);
            JZMap.addOverlay(marker);
        },
        removeOverlay:function(){
            JZMap.clearOverlays();
        },
        setMap:function(point,zoom){

            var that=this,evtTimer=[];
            JZMap.centerAndZoom(point, zoom);
            JZMap.enableScrollWheelZoom();
            JZMap.setMinZoom(9);
            that.addMaxMin();
            that.setZoneData();
        },
        setZoneData:function(){
            // set data
            var dt = [];
            var that = this;
            that.iniMapDataRender(dt);
        },
        initMap:function(){

            var that = this;
            JZMap = new BMap.Map("map");
            window.JZMap=JZMap;
            that.getPoint();
        }
    }

    document.addEventListener('DOMContentLoaded',function(){

        // function resetH(){
            
        //     adjustH();
        //     $(".map-list").slimScroll();
        //     $('.slimScrollDiv').css('width','100%');
        // }
        // resetH();
        adjustH();
        function adjustH(){
            var Theight = $('.map-nav__padding').height();
            var Hheight = $('.map').height();
            var bHeight = Hheight - Theight -16;

            $(".map-list").css('height', bHeight)
        }
        // map init
        // 异步 通过构造函数（回调函数导致执行顺序的不一致）传参 解决函数的回调
        var cons = {
            doGet: doGet,
            searchAround: searchAround
        }
        var jmp=new jMap(cons);
        jmp.init();

        // left right
        $('.map-arrow').on('click', function(){
            var navbar = $('.map-nav');
            if(navbar.hasClass('off')){
                navbar.removeClass('off');
            }
            else
            {
                navbar.addClass('off');
            }
        })

/************************************************** 逻辑 **************************************************************/ 
        // alert
        var $a = $('.common');
        var $bg = $('.modal-bg');
        var $inner = $('.modal-inner');
        var action = {
            'modal': modal,
            'removeModal': removeModal
        }
        
        function modal(){
            $bg.addClass('on');
            $inner.addClass('on');
        }
        function removeModal(){
            $bg.removeClass('on');
            $inner.removeClass('on');
        }
        $a.on('click', function(){
            action[$(this).data('action')]();
        });

        var params = {
            regionCode: '',
            rent: '',
            houseType: '',
            rentType: '',
            roomNum: '',
            order: ''
        }

        var url_get = '/map?regionCode=[:regionCode]&rent=[:rent]&houseType=[:houseType]&rentType&[:rentType]&roomNum=[:roomNum]&order=[:order]'

        //page init
        var stylePage = {
            count                   : 6,
            Pbegain                 : 0,  // 列表初始位置
            Pfactor                 : 8,  // 列表展示条数
            Parray                  : [],  // 列表展示存储
            start                   : 1,
            display                 : 5,
            border                  : true,
            border_color            : 'rgba(0,0,0,0.15)',
            text_color              : 'rgba(0,0,0,0.8)',
            background_color        : '#fff',  
            border_hover_color      : '#FF4354',
            text_hover_color        : '#fff',
            background_hover_color  : '#FF4354', 
            images                  : false,
            mouse                   : 'press',
            rotate                  : false,
            onChange                : function(page){
                                        console.log(page);
                                        templateData(page - 1);
                                    }
        } 
        
        function insertArray(data){
            stylePage.Parray = data;
            stylePage.count = Math.ceil((data.length)/stylePage.Pfactor);
        }

        function reverseParams(params){
            return url_get.replace("[:regionCode]",params.regionCode)
                           .replace("[:rent]",params.rent)
                           .replace("[:houseType]",params.houseType)
                           .replace("[:rentType]",params.rentType)
                           .replace("[:roomNum]",params.roomNum)
                           .replace("[:order]",params.order)
        }

        function renderMap(data){
            jmp.iniMapDataRender(data)
        }

        function templateAjax(html){
            $('.filter-detail .items').empty();
            $('.filter-detail .items').append(html);
        }
        function templateData(num){
            var data = {
                list: stylePage.Parray.slice(num*stylePage.Pfactor,(num + 1)*stylePage.Pfactor)
            };
            var html = template('mapTem', data);
            templateAjax(html);
        }
        function templateHtml(data){
            var data = {
                list: data.list.slice(stylePage.Pbegain,stylePage.Pfactor)
            };
            var html = template('mapTem', data);
            templateAjax(html)
            $('#page').empty();
            $("#page").paginate(stylePage);
        }
        function doGet(flag){

            if(flag){
                var initParam = $.extend(params,roomFilter);
                // console.log(params);
                console.log(params);
                var URL_GET = reverseParams(initParam);
            }
            else
            {
                var URL_GET = reverseParams(params);
            }

            
            $.get(URL_GET,function(data){
                if(!data.result){
                    return  modal();
                }
                if(data.list.length ==0){
                    // return alert('该条件没有房源。');
                    modal();
                }
                insertArray(data.list);
                templateHtml(data);
                renderMap(data.regionViews);
            },'json')
        }

        // order
        $order = $('.site-search .item');
        function orderBy(obj,tag){

            if(obj.find('i').hasClass('down')){
                obj.find('i').removeClass('down').addClass('up');
                if(obj.hasClass('map')){
                    $order.removeClass('on');
                    obj.addClass('on');
                }
                var para = JSON.parse(obj[0].getAttribute('data-param'));
                $.extend(params,para);
                doGet()

            }
            else
            {
                obj.find('i').removeClass('up').addClass('down');
                if(obj.hasClass('map')){
                    $order.removeClass('on');
                    obj.addClass('on')
                }
                var para = JSON.parse(obj[0].getAttribute('data-down'));
                $.extend(params,para);
                doGet()
            }
        }
        $order.on('click',function(){
            orderBy($(this),true)
        })

        // region filter
        $li = $('.filter-list li');
        function filterFactors(li){
            if(li.hasClass('active')){
                    return
            }
            li.addClass('active');
            li.siblings().removeClass('active');
            $.extend(params,li.data('param'));
            doGet();
            adjustH();
        }
        
        $li.on('click.site',function(){
            filterFactors($(this));
        })

        // code filter
        $ul = $('.filter-list').eq(0).find('li')
        $region   = $('.filter-rigion');

        function ifRegion(index){

            $region.css('display','none');
            if($region.eq(index).find('a')){
                $region.eq(index).css('display','block');
            }
            
        }
        $ul.on('click.site',function(){

            if($(this).index() == 0){          
                $region.css('display', 'none');
            }
            else
            {
                var index = $(this).index() -1;
                ifRegion(index);
                adjustH();
            }
        })
        $region.find('a').on('click', function(e){

            e.preventDefault();
            e.stopPropagation();
            if($(this).hasClass('on')){
                return
            }
            $region.find('a').removeClass('on');
            $(this).addClass('on');
            $.extend(params,$(this).data('param'));
            doGet();
        })

        // search around
        var search_url = '/map/search?longitude=[:longitude]&latitude=[:latitude]&distance=[:distance]';
        function dareach(url){
            $.get(url,function(data){
                console.log(data);
                if(!data.result){
                    return  modal();
                }
                insertArray(data.list);
                templateHtml(data);
                renderMap(data.regionViews);
            },'json')
        }

        function reverseSearch(params){
            return search_url.replace("[:longitude]",params.lng)
                             .replace("[:latitude]",params.lat)
                             .replace("[:distance]",params.distance)
        }
        function searchAround(point){

            var Selected = $('.far-away option:selected').val() || 100;
            point.distance = Selected;

            var SEARCH_URL = reverseSearch(point);
            console.log(SEARCH_URL);
            dareach(SEARCH_URL)
        }


        $('.search-around').on('click', function(){
            var Around = $('input[name="region-around"]').val();
            console.log(Around);
            jmp.getMapGeocoder(Around);
        })

    },false);
})();
